package com.yunfeisoft.controller;

import com.yunfeisoft.common.base.BaseModel;
import com.yunfeisoft.common.session.WebDomainContext;
import com.yunfeisoft.common.utils.AjaxUtils;
import com.yunfeisoft.common.utils.WebUtils;
import com.yunfeisoft.utils.ApiUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
public class ViewController {

    @Autowired
    private WebDomainContext webDomainContext;
    @Value("${default.index}")
    private String defaultIndex;

    @Value("${file.request.url}")
    private String fileRequestUrl;
    //@Resource
    //private Map<String, String> properties;

    /**
     * js、css页面随机参数，防止缓存
     */
    private static final String PAGE_RANDOM = String.valueOf(System.currentTimeMillis());

    @RequestMapping("/view/{dir1}/{dir2}/{page}")
    public String view(@PathVariable("dir1") String dir1, @PathVariable("dir2") String dir2, @PathVariable("page") String page, HttpServletRequest request) {
        if (StringUtils.isEmpty(dir1) || StringUtils.isEmpty(dir2)
                || StringUtils.isEmpty(page)) {
            return "error/404";
        }
        gainParams(request);
        return dir1 + "/" + dir2 + "/" + page;
    }

    @RequestMapping("/view/{dir}/{page}")
    public String view(@PathVariable("dir") String dir, @PathVariable("page") String page, HttpServletRequest request) {
        if (StringUtils.isEmpty(dir) || StringUtils.isEmpty(page)) {
            return "error/404";
        }
        gainParams(request);
        return dir + "/" + page;
    }

    @RequestMapping("/view/{page}")
    public String view(@PathVariable("page") String page, HttpServletRequest request) {
        if (StringUtils.isEmpty(page)) {
            return "error/404";
        }
        gainParams(request);
        return page;
    }

    @RequestMapping("/{page}")
    public String page(@PathVariable("page") String page, HttpServletRequest request) {
        if (StringUtils.isEmpty(page)) {
            return "error/404";
        }
        gainParams(request);
        return page;
    }

    @RequestMapping("/")
    public String index(HttpServletRequest request) {
        setRemoteUrl(request);
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        WebUtils.gainParams(paramsMap);
        request.setAttribute("params", paramsMap);

        paramsMap.put("contextPath", webDomainContext.getWebDomain());
        paramsMap.put("pageRandom", PAGE_RANDOM);
        paramsMap.put("fileRequestUrl", fileRequestUrl);
        return defaultIndex;
    }

    private void gainParams(HttpServletRequest request) {
        setRemoteUrl(request);
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        //paramsMap.putAll(properties);
        WebUtils.gainParams(paramsMap);
        request.setAttribute("params", paramsMap);

        paramsMap.put("contextPath", webDomainContext.getWebDomain());
        paramsMap.put("pageRandom", PAGE_RANDOM);
        paramsMap.put("fileRequestUrl", fileRequestUrl);

        BaseModel user = ApiUtils.getLogin();
        request.setAttribute("user", user);
        //System.out.println("##### = " + properties);
    }

    private void setRemoteUrl(HttpServletRequest request) {
        if (StringUtils.isNotBlank(webDomainContext.getWebDomain()) && !webDomainContext.getWebDomain().equals(webDomainContext.getContextPath())) {
            return;
        }
        String requestUrl = request.getRequestURL().toString().toLowerCase();
        StringBuilder builder = new StringBuilder();
        if (requestUrl.startsWith("https://")) {
            builder.append("https://");
        } else {
            builder.append("http://");
        }

        builder.append(request.getServerName())
                .append(":")
                .append(request.getServerPort())
                .append(request.getContextPath());

        webDomainContext.setWebDomain(builder.toString());
    }

    @RequestMapping("/web/keepAlive")
    public void keepAlive(HttpServletRequest request, HttpServletResponse response) {
        AjaxUtils.ajaxJsonSuccessMessage("SUCCESS");
    }
}
